// 版权声明，Epic Games 公司保留所有权利

#include "IPickupable.h"

#include "GameFramework/Actor.h"
#include "LyraInventoryManagerComponent.h"
#include "UObject/ScriptInterface.h"

#include UE_INLINE_GENERATED_CPP_BY_NAME(IPickupable)

class UActorComponent;

/**
 * 构造函数
 */
UPickupableStatics::UPickupableStatics()
	: Super(FObjectInitializer::Get())
{
}

/**
 * 从Actor获取第一个可拾取对象
 * @param Actor 要检查的Actor
 * @return 可拾取对象的脚本接口
 */
TScriptInterface<IPickupable> UPickupableStatics::GetFirstPickupableFromActor(AActor* Actor)
{
	// 如果Actor直接可拾取，返回该Actor
	TScriptInterface<IPickupable> PickupableActor(Actor);
	if (PickupableActor)
	{
		return PickupableActor;
	}

	// 如果Actor不可拾取，可能有一个组件具有可拾取接口
	TArray<UActorComponent*> PickupableComponents = Actor ? Actor->GetComponentsByInterface(UPickupable::StaticClass()) : TArray<UActorComponent*>();
	if (PickupableComponents.Num() > 0)
	{
		// 获取第一个可拾取组件，如果需要更复杂的拾取区分，需要在其他地方解决
		return TScriptInterface<IPickupable>(PickupableComponents[0]);
	}

	return TScriptInterface<IPickupable>(); // 返回空接口
}

/**
 * 将拾取物添加到库存
 * @param InventoryComponent 库存管理组件
 * @param Pickup 可拾取对象
 */
void UPickupableStatics::AddPickupToInventory(ULyraInventoryManagerComponent* InventoryComponent, TScriptInterface<IPickupable> Pickup)
{
	if (InventoryComponent && Pickup)
	{
		const FInventoryPickup& PickupInventory = Pickup->GetPickupInventory(); // 获取拾取库存

		// 遍历模板数组
		for (const FPickupTemplate& Template : PickupInventory.Templates)
		{
			InventoryComponent->AddItemDefinition(Template.ItemDef, Template.StackCount); // 添加物品定义
		}

		// 遍历实例数组
		for (const FPickupInstance& Instance : PickupInventory.Instances)
		{
			InventoryComponent->AddItemInstance(Instance.Item); // 添加物品实例
		}
	}
}